package cn.cttic.order.dubbo;

import cn.cttic.common.core.exception.order.OrderException;
import cn.cttic.common.core.utils.BeanCopyUtils;
import cn.cttic.order.api.RemoteInstallOrderService;
import cn.cttic.order.api.domain.BaseInstallOrder;
import cn.cttic.order.api.domain.bo.BaseInstallOrderBo;
import cn.cttic.order.api.domain.vo.BaseInstallOrderVo;
import cn.cttic.order.service.IBaseInstallOrderProcessService;
import cn.cttic.order.service.IBaseInstallOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.apache.dubbo.config.annotation.DubboService;

import java.time.LocalDateTime;

@DubboService
@Slf4j
@RequiredArgsConstructor
public class RemoteInstallOrderServiceImpl implements RemoteInstallOrderService {

    private final IBaseInstallOrderService baseInstallOrderService;

    private final IBaseInstallOrderProcessService baseInstallOrderProcessService;

    /**
     * 设备上线
     *
     * @param imei
     * @param onlineTime
     * @param interfaceId
     * @return
     */
    @Override
    public boolean deviceOnline(String imei, LocalDateTime onlineTime, String interfaceId) {

        String orderId = baseInstallOrderProcessService.getOrderIdByImei(imei);
        if (orderId == null) {
            throw new OrderException("未找到安装订单");
        }

        BaseInstallOrderVo installOrder = baseInstallOrderService.queryById(orderId);
        installOrder.setOnlineInterfaceId(interfaceId);
        installOrder.setOnlineTime(onlineTime);

        if (baseInstallOrderService.updateByBo(BeanCopyUtils.copy(installOrder, BaseInstallOrderBo.class))) {
            return true;
        } else {
            throw new OrderException("更新订单信息失败");
        }
    }

    /**
     * 设备激活
     *
     * @param imei
     * @param activeTime
     * @param lastOnlineTime
     * @param interfaceId
     * @return
     */
    @Override
    public boolean deviceActive(String imei, LocalDateTime activeTime, LocalDateTime lastOnlineTime, String interfaceId) {

        String orderId = baseInstallOrderProcessService.getOrderIdByImei(imei);
        if (orderId == null) {
            throw new OrderException("未找到安装订单");
        }

        BaseInstallOrderVo installOrder = baseInstallOrderService.queryById(orderId);
        installOrder.setActiveInterfaceId(interfaceId);
        installOrder.setLastOnlineTime(lastOnlineTime);
        installOrder.setActiveTime(activeTime);

        if (baseInstallOrderService.updateByBo(BeanCopyUtils.copy(installOrder, BaseInstallOrderBo.class))) {
            return true;
        } else {
            throw new OrderException("更新订单信息失败");
        }
    }
}
